<?php
class grade extends core {
	public function __construct() {
		parent::__construct();
	}

	//index
	public function index() {
		$where = '';
		$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : '';
		$keyword = (isset($_GET['keyword']) && trim($_GET['keyword'])) ? trim($_GET['keyword']) : '';
		if ($id) {
			$where .= " AND id='{$id}'";
		}
		if ($keyword) {
			$where .= " AND (name LIKE '%{$keyword}%' OR memo LIKE '%{$keyword}%')";
		}
		//分页
		$this->setpages(array('id'=>$id, 'keyword'=>$keyword));

		$sql = "SELECT * FROM {$this->tbp}member_grade WHERE 1 {$where} ORDER BY sort ASC, id ASC";
		$rs = $this->ezr->get_results($sql);
		$nav = $this->ezr->get_navigation();
		$this->smarty->assign('rs',$rs);
		$this->smarty->assign('page',$nav);

		$this->display();
	}

	public function add() {
		if (IS_POST) {
			$this->save();
		} else {
			$this->display();
		}
	}

	//add
	public function edit() {
		if (IS_POST) { //添加
			$this->save();
		} else { //显示
			$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : 0;
			$sql = "SELECT * FROM {$this->tbp}member_grade WHERE id='{$id}'";
			$row = $this->db->get_row($sql);
			$this->smarty->assign('row', $row);
			$this->display();
		}
	}

	//写入到数据库
	public function save() {
		$id = (isset($_POST['id']) && trim($_POST['id'])) ? intval($_POST['id']) : 0;
		$name = (isset($_POST['name']) && trim($_POST['name'])) ? trim($_POST['name']) : 0;
		$memo = (isset($_POST['memo']) && trim($_POST['memo'])) ? trim($_POST['memo']) : '';
		$score = (isset($_POST['score']) && intval($_POST['score'])) ? intval($_POST['score']) : 0;
		$price = (isset($_POST['price']) && floatval($_POST['price'])) ? floatval($_POST['price']) : 0;
		$status = (isset($_POST['status']) && intval($_POST['status'])) ? intval($_POST['status']) : 0;
		$sort = (isset($_POST['sort']) && intval($_POST['sort'])) ? intval($_POST['sort']) : 0;
		$pic = upload_one_file('pic','pic');
		if (!$pic) $pic = (isset($_POST['origin_pic']) && trim($_POST['origin_pic'])) ? trim($_POST['origin_pic']) : '';
		if ($id > 0) {  //edit
			$sql = "UPDATE {$this->tbp}member_grade SET name='{$name}', memo='{$memo}', score='{$score}', 
				price='{$price}', pic='{$pic}', status='{$status}', sort='{$sort}' WHERE id='{$id}'";
			$this->db->query($sql);
		} else { //add
			$sql = "INSERT INTO {$this->tbp}member_grade(name, memo, score, price, pic, status, sort)
				VALUES('{$name}', '{$memo}', '{$score}', '{$price}', '{$pic}', '{$status}', '{$sort}')";
			$this->db->query($sql);
			$id = $this->db->insert_id;
		}
		header("Location:?app=grade&act=index");
	}

	//delete
	public function delete() {
		$id = (isset($_GET['id']) && trim($_GET['id'])) ? intval($_GET['id']) : 0;
		$sql = "DELETE FROM {$this->tbp}member_grade WHERE id='{$id}'";
		$this->db->query($sql);
		header("Location:?app=grade&act=index");
	}
}
